<?php
namespace Bootstrap;
class MultiBoot
{
    public $di;

    function register()
    {
        $config = $this->di->getShared("config");
        $modules = array();

        foreach ($config->modules->toArray() as $k => $v) {

            $modules[$k] = function ($di) use ($k, $v) {
                $loader = $di->getShared("loader");
                //加载模块配置文件
                $module_config_file = APP_PATH . "/" . ucwords($k) . "/Conf/config.php";
                if (file_exists($module_config_file)) {
                    $di->setShared("module_config", new \Phalcon\Config(include $module_config_file));
                }
                //设置自动加载
                if (isset($v['autoload']) && is_array($v['autoload']) && !empty($v['autoload'])) {
                    $loader->registerNamespaces(array_merge($loader->getNamespaces(), $v['autoload']));//注册命名空间
                    $loader->register();//完成自动加载的注册

                }
                //设置分发器服务
                $di->setShared('dispatcher', function () use ($di, $k, $v) {
                    $dispatcher = new \Phalcon\Mvc\Dispatcher();
                    $dispatcher->setDefaultNamespace($v['namespace'] . "\Controllers\\");//设置控制器默认命名空间
                    return $dispatcher;
                });
                //设置视图服务
                $di->setShared('view', function () use ($di, $k, $v) {
                    $view = new \Phalcon\Mvc\View();
                    $view->setViewsDir(APP_PATH . "/" . ucwords($k) . "/Views/");//设定视图目录
                    return $view;
                });
            };
        }
        $this->di->getShared("application")->registerModules($modules);
    }

    function setDi(\Phalcon\DI $di)
    {
        $this->di = $di;

        return $this;
    }
}